/**
 * 
 */
package com.yidin.util;

import java.io.File;
import java.io.InputStream;

import com.yidin.lsc.LscActivity;
import com.yidin.util.HttpAdapter.OnHttpResponse;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;

/**
 * 网络图片基类
 * 
 * @author cola
 * 
 */
public class NetImageBase implements IImage {

	private Handler handler;
	// private String logoPath;

	/**
	 * 图片回调接口
	 */
	public imageCallback ic;
	public String path;

	public Bitmap getLocalBitmap(Handler handler, Context ctx, String url,
			int width, int hight) {
		String path = FileAdapter.getSdCardRootDir()
				+ LscActivity.SERVER_DATA_PATH + HttpAdapter.getUrlFileName(url);
		if (path != null && path.length() > 0) {
			return ImageAdapter.getLocalBitmap(path, width, hight);
		}
		return null;
	}

	public Bitmap getLogoBitmap(Handler handler, Context ctx, String path,
			imageCallback ic) {
		this.path = path;
		this.handler = handler;
		this.ic = ic;
		File file = new File(FileAdapter.getSdCardRootDir()
				+ LscActivity.SERVER_DATA_PATH + HttpAdapter.getUrlFileName(path));
		// if (logoPath != null && logoPath.length() > 0) {
		if (file != null && file.length() > 0) {
			return ImageAdapter.getLocalBitmap(file.getAbsolutePath(),
					60,60);
		}

		getLogoByNet(ctx, path);
		// 获取本地默认图标
		return null;
	}

	private void getLogoByNet(Context ctx, String path) {
		OnHttpResponse response = new OnHttpResponse() {
			public void onResponse(String url, boolean isOk, String err,
					long size, InputStream inStream) {
				if (!isOk){
					Message message = handler.obtainMessage(0,
							NetImageBase.this);
					message.what = 4;
					handler.sendMessage(message);
					return;
				}

				String path = url.substring(url.lastIndexOf("/") + 1,
						url.length());
				path = FileAdapter.getSdCardRootDir() + LscActivity.SERVER_DATA_PATH + path;
				if (FileAdapter.writeFile(path, inStream)) {
					Message message = handler.obtainMessage(0,
							NetImageBase.this);
					message.what = 5;
					handler.sendMessage(message);
				}
			}
		};

		if (path != null && path.length() > 0) {
			HttpAdapter.getDefault(ctx).requestAsync(path, null, null, false,
					response);
		}
	}

	public void cancelLogoBitmap(Handler handler) {
		// TODO Auto-generated method stub
		
	}

}
